package com.example.fileserver_API.Interfaces.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.fileserver_API.Dao.SysappsettingMappers;
import com.example.fileserver_API.Dao.UploadpicturesMappers;
import com.example.fileserver_API.Entity.PO.sysappsettings;
import com.example.fileserver_API.Entity.PO.uploadpictures;
import com.example.fileserver_API.Entity.VO.APIResult;
import com.example.fileserver_API.FixedValue.SetSettings;
import com.example.fileserver_API.Interfaces.IService.IUploadService;
import com.example.fileserver_API.Interfaces.IService.IUploadpicturesService;
import com.example.fileserver_API.utils.APIResultImg;
import com.example.fileserver_API.utils.APIResultUtils;
import com.example.fileserver_API.utils.RedisUtils;
import com.example.fileserver_API.utils.StringUtils;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

import static com.example.fileserver_API.utils.ResizeImageUtils.resizeImage;

@Service
public class UploadService implements IUploadService {
    @Resource
    IUploadpicturesService _iUploadpicturesService;
    @Resource
    RedisUtils redisUtils;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    /**
     * 普通的上传图片
     * @param file 文件
     * @return APIResult
     */
    @Override
    public APIResult Upload(MultipartFile file, HttpServletRequest req) {
        List<String> allowedTypes = new ArrayList<>(Arrays.asList("image/jpeg", "image/png","image/jpg"));
        String contentType = file.getContentType();
        if (contentType != null && allowedTypes.contains(contentType)) {
            // 设置上传文件的最大大小，这里设置为5MB
            final long MAX_SIZE = 5 * 1024 * 1024;
            if (file.getSize() > MAX_SIZE) {
                return APIResultUtils.error("上传文件过大");
            }
            // 查询上传目录位置
            String realpath = redisUtils.GetHashValue(SetSettings.sys_syssetting,SetSettings.sys_path).toString();
            if (StringUtils.isBlank(realpath))
                return APIResultImg.error("未配置path的设置");
            String prefix = "Img/";// 前缀
            String format = sdf.format(new Date());// 文件夹时间分类
            File folder = new File(realpath+prefix+format);
            if (!folder.isDirectory()){
                folder.mkdirs();
            }
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
            try {
                file.transferTo(new File(folder,newName));
                String filepath = prefix+format+"/"+newName;
                APIResult apiResult = _iUploadpicturesService.AddPicRecord(oldName,newName,file.getSize(),filepath,oldName.substring(oldName.lastIndexOf("."),oldName.length()),"Img","图片");
                return APIResultImg.success("上传成功",apiResult.getData().toString(),filepath,"图片",filepath);
            }catch (IOException e){
                return APIResultImg.error(e.getMessage());
            }
        } else {
            // 不允许上传的图片类型
            return APIResultImg.error("不是上传需要的文件类型！");
        }
    }

    /**
     * 上传用户头像
     * @param file 文件
     * @param req req
     * @return APIResult
     */
    @Override
    public APIResult UploadUser(MultipartFile file, HttpServletRequest req) {
        List<String> allowedTypes = new ArrayList<>(Arrays.asList("image/jpeg", "image/png","image/jpg"));
        String contentType = file.getContentType();
        if (contentType != null && allowedTypes.contains(contentType)) {
            // 设置上传文件的最大大小，这里设置为5MB
            final long MAX_SIZE = 5 * 1024 * 1024;
            if (file.getSize() > MAX_SIZE) {
                return APIResultUtils.error("上传文件过大");
            }
            // 查询上传目录位置
            String realpath = redisUtils.GetHashValue(SetSettings.sys_syssetting,SetSettings.sys_path).toString();
            if (StringUtils.isBlank(realpath))
                return APIResultImg.error("未配置path的设置");
            String prefix = "User/";// 前缀
            String format = sdf.format(new Date());// 文件夹时间分类
            File folder = new File(realpath+prefix+format);
            if (!folder.isDirectory()){
                folder.mkdirs();
            }
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
            try {
                file.transferTo(new File(folder,newName));
                String filepath = prefix+format+"/"+newName;
                APIResult apiResult = _iUploadpicturesService.AddPicRecord(oldName,newName,file.getSize(),filepath,oldName.substring(oldName.lastIndexOf("."),oldName.length()),"User","头像");
                return APIResultImg.success("上传成功",apiResult.getData().toString(),filepath,"头像",filepath);
            }catch (IOException e){
                return APIResultImg.error(e.getMessage());
            }
        } else {
            // 不允许上传的图片类型
            return APIResultImg.error("不是上传需要的文件类型！");
        }
    }

    /**
     * 带水印的上传(书写作品上传的图片带水印)
     * @param file 文件
     * @return @Override
     */
    @Override
    public APIResult Uploadwatermark(MultipartFile file, HttpServletRequest req){
        List<String> allowedTypes = new ArrayList<>(Arrays.asList("image/jpeg", "image/png", "image/jpg"));
        String contentType = file.getContentType();
        if (contentType != null && allowedTypes.contains(contentType)) {
            // 设置上传文件的最大大小，这里设置为5MB
            final long MAX_SIZE = 5 * 1024 * 1024;
            if (file.getSize() > MAX_SIZE) {
                return APIResultUtils.error("上传文件过大");
            }
            // 查询上传目录位置
            String realpath = redisUtils.GetHashValue(SetSettings.sys_syssetting,SetSettings.sys_path).toString();
            if (StringUtils.isBlank(realpath))
                return APIResultImg.error("未配置path的设置");
            String prefix = "Illustration/";// 前缀
            String format = sdf.format(new Date());// 文件夹时间分类

            File folder = new File(realpath + prefix + format);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }

            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
            try {
                file.transferTo(new File(folder, newName));
                String filepath = realpath + prefix + format + "/" + newName;
                // 查询应用水印
                String syswatermarkimg = redisUtils.GetHashValue(SetSettings.sys_syssetting,SetSettings.sys_watermarkimgpath).toString();
                if (StringUtils.isEmpty(syswatermarkimg))
                    return APIResultUtils.error("未查询到配置的水印位置");
                // 应用水印
                String watermarkPath = realpath+syswatermarkimg; // 替换为水印图片文件的实际路径
                String outputImagePath = folder.getPath() + "/" + newName; // 带水印图像的输出路径

                BufferedImage originalImage = ImageIO.read(new File(filepath));
                BufferedImage watermarkedImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_RGB);

                Graphics2D graphics2D = (Graphics2D) watermarkedImage.getGraphics();
                graphics2D.drawImage(originalImage, 0, 0, null);

                // 调整水印透明度
                float alpha = 0.8f; // 水印透明度（0.0为完全透明，1.0为完全不透明）
                graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
                File watermarkFile = new File(watermarkPath);
                BufferedImage watermarkImage = ImageIO.read(watermarkFile);

                int targetWidth = originalImage.getWidth() / 8;
                int targetHeight = originalImage.getHeight() / 8;

                // 调整水印图片大小
                watermarkImage = resizeImage(watermarkImage, targetWidth, targetHeight);

                // 计算出现的位置信息
                int watermarkX = watermarkedImage.getWidth() - watermarkImage.getWidth() - 10; // 水印位置：距离右边10个像素
                int watermarkY = watermarkedImage.getHeight() - watermarkImage.getHeight() - 50; // 水印位置：距离底部50个像素
                graphics2D.drawImage(watermarkImage, watermarkX, watermarkY, null);

                graphics2D.dispose();
                ImageIO.write(watermarkedImage, "jpg", new File(outputImagePath));
                // 将带水印的图像详细信息添加到数据库或执行任何其他所需的操作
                APIResult apiResult = _iUploadpicturesService.AddPicRecord(oldName, newName, file.getSize(), prefix+format+"/"+newName,oldName.substring(oldName.lastIndexOf("."), oldName.length()),"Illustration","水印图片");
                return APIResultImg.success("上传成功",apiResult.getData().toString(), outputImagePath, "水印图片", outputImagePath);
            }
            catch (IOException e) {
                return APIResultImg.error(e.getMessage());
            }
        }
        else {
            // 不允许上传的图片类型
            return APIResultImg.error("不是上传需要的文件类型！");
        }
    }

    /**
     * 上传资源
     * @param file 资源文件
     * @return @Override
     */
    @Override
    public APIResult UploadResoure(MultipartFile file, HttpServletRequest req) {
        // 设置上传文件的最大大小，这里设置为10MB
        final long MAX_SIZE = 10 * 1024 * 1024;
        if (file.getSize() > MAX_SIZE) {
            return APIResultUtils.error("上传文件过大");
        }
        // 查询上传目录位置
        String realpath = redisUtils.GetHashValue(SetSettings.sys_syssetting,SetSettings.sys_path).toString();
        if (StringUtils.isBlank(realpath))
            return APIResultImg.error("未配置path的设置");

        String prefix = "Resource/";// 前缀
        String format = sdf.format(new Date());// 文件夹时间分类
        File folder = new File(realpath+prefix+format);
        if (!folder.isDirectory()){
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
        try {
            file.transferTo(new File(folder,newName));
            String filepath = prefix+format+"/"+newName;
            APIResult apiResult = _iUploadpicturesService.AddPicRecord(oldName,newName,file.getSize(),filepath,oldName.substring(oldName.lastIndexOf("."),oldName.length()),"Resource","资源");
            return APIResultImg.success("上传成功",apiResult.getData().toString(),filepath,"资源",filepath);
        }
        catch (IOException e){
            return APIResultImg.error(e.getMessage());
        }
    }

    /**
     * 上传app文件
     * @param file app文件
     * @return APIResult
     */
    @Override
    public APIResult UploadAppFile(MultipartFile file) {
        // 设置上传文件的最大大小，这里设置为100MB
        final long MAX_SIZE = 100 * 1024 * 1024;
        if (file.getSize() > MAX_SIZE) {
            return APIResultUtils.error("上传文件过大");
        }
        // 查询上传目录位置
        String realpath = redisUtils.GetHashValue(SetSettings.sys_syssetting,SetSettings.sys_path).toString();
        if (StringUtils.isBlank(realpath))
            return APIResultImg.error("未配置path的设置");

        String prefix = "AppFile/";// 前缀
        String format = sdf.format(new Date());// 文件夹时间分类
        File folder = new File(realpath+prefix+format);
        if (!folder.isDirectory()){
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
        try {
            file.transferTo(new File(folder,newName));
            String filepath = prefix+format+"/"+newName;
            APIResult apiResult = _iUploadpicturesService.AddPicRecord(oldName,newName,file.getSize(),filepath,oldName.substring(oldName.lastIndexOf("."),oldName.length()),"AppFile","APP");
            return APIResultImg.success("上传成功",apiResult.getData().toString(),filepath,"APP",filepath);
        }
        catch (IOException e){
            return APIResultImg.error(e.getMessage());
        }
    }

    /**
     * 上传视频
     * @param videoFile 视频文件
     * @return APIResult
     */
    @Override
    public APIResult handleVideoUpload(MultipartFile videoFile) {
        if (videoFile.isEmpty()) {
            return APIResultUtils.error("请选择一个视频进行上传！");
        }
        // 检查文件类型是否为MP4
        if (!videoFile.getOriginalFilename().toLowerCase().endsWith(".mp4")) {
            return APIResultUtils.error("仅允许上传MP4格式的视频文件！");
        }
        try {
            // 查询上传目录位置
            String realpath = redisUtils.GetHashValue(SetSettings.sys_syssetting,SetSettings.sys_path).toString();
            if (StringUtils.isBlank(realpath))
                return APIResultImg.error("未配置path的设置");
            String format = sdf.format(new Date());// 文件夹时间分类
            String oldName = videoFile.getOriginalFilename();
            String newName = UUID.randomUUID()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
            String fix = "Video\\"+format+"\\"+newName;
            realpath += fix;// 前缀
            File folder = new File(realpath);
            if (!folder.isDirectory()){
                folder.mkdirs();
            }
            // 构建保存文件的路径
            File file = new File(realpath);
            videoFile.transferTo(file); // 保存文件到服务器
            APIResult apiResult = _iUploadpicturesService.AddPicRecord(oldName,newName,videoFile.getSize(),fix,oldName.substring(oldName.lastIndexOf("."),oldName.length()),"Video","视频");
            return APIResultImg.success("上传成功",apiResult.getData().toString(),fix,"视频",realpath);
        } catch (Exception e) {
            return APIResultImg.error(e.getMessage());
        }
    }
}
